<template>
  <div class="admin-dashboard-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">管理仪表盘</h1>
      <p class="page-subtitle">欢迎管理员，这里是平台运行概览</p>
    </div>

    <!-- 核心数据概览 -->
    <div class="stats-overview">
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalUsers }}</span>
          <span class="stat-label">用户总数</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value positive">{{ userGrowth }}%</span>
          <span class="trend-label">较上月</span>
        </div>
        <el-icon class="stat-icon"><User /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalPosts }}</span>
          <span class="stat-label">帖子总数</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value positive">{{ postGrowth }}%</span>
          <span class="trend-label">较上月</span>
        </div>
        <el-icon class="stat-icon"><Message /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalQuestions }}</span>
          <span class="stat-label">题目总数</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value positive">{{ questionGrowth }}%</span>
          <span class="trend-label">较上月</span>
        </div>
        <el-icon class="stat-icon"><Document /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalGroups }}</span>
          <span class="stat-label">学习小组</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value positive">{{ groupGrowth }}%</span>
          <span class="trend-label">较上月</span>
        </div>
        <el-icon class="stat-icon"><UserFilled /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalResources }}</span>
          <span class="stat-label">学习资源</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value positive">{{ resourceGrowth }}%</span>
          <span class="trend-label">较上月</span>
        </div>
        <el-icon class="stat-icon"><Folder /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalVisits }}</span>
          <span class="stat-label">今日访问量</span>
        </div>
        <div class="stat-trend">
          <span class="trend-value" :class="visitTrend > 0 ? 'positive' : 'negative'">{{ Math.abs(visitTrend) }}%</span>
          <span class="trend-label">较昨日</span>
        </div>
        <el-icon class="stat-icon"><View /></el-icon>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>用户增长趋势</span>
            <el-select v-model="chartTimeRange" placeholder="选择时间范围" class="chart-filter">
              <el-option label="近7天" value="7d" />
              <el-option label="近30天" value="30d" />
              <el-option label="近90天" value="90d" />
              <el-option label="近12个月" value="12m" />
            </el-select>
          </div>
        </template>
        <div class="chart-container">
          <canvas ref="userGrowthChart" width="400" height="200"></canvas>
        </div>
      </el-card>
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>活跃用户分布</span>
            <el-select v-model="activeUserFilter" placeholder="选择类型" class="chart-filter">
              <el-option label="按地区" value="region" />
              <el-option label="按兴趣" value="interest" />
              <el-option label="按角色" value="role" />
            </el-select>
          </div>
        </template>
        <div class="chart-container">
          <canvas ref="userDistributionChart" width="400" height="200"></canvas>
        </div>
      </el-card>
    </div>

    <!-- 最近活动和待办事项 -->
    <div class="dashboard-bottom">
      <!-- 最近活动 -->
      <el-card class="activity-card">
        <template #header>
          <div class="card-header">
            <span>最近活动</span>
            <el-button type="text" size="small" @click="viewAllActivities">查看全部</el-button>
          </div>
        </template>
        <div class="activities-list">
          <div v-for="activity in recentActivities" :key="activity.id" class="activity-item">
            <div class="activity-icon">
              <el-icon :class="getActivityIconClass(activity.type)">
                {{ getActivityIcon(activity.type) }}
              </el-icon>
            </div>
            <div class="activity-content">
              <p class="activity-text">{{ activity.content }}</p>
              <p class="activity-time">{{ activity.time }}</p>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 待办事项 -->
      <el-card class="todo-card">
        <template #header>
          <div class="card-header">
            <span>待办事项</span>
            <el-button type="text" size="small" @click="addTodoItem">添加</el-button>
          </div>
        </template>
        <div class="todo-list">
          <div v-for="todo in todoItems" :key="todo.id" class="todo-item">
            <el-checkbox v-model="todo.completed" @change="updateTodoStatus(todo)">{{ todo.content }}</el-checkbox>
            <div class="todo-actions">
              <el-button type="text" size="small" @click="editTodoItem(todo)">编辑</el-button>
              <el-button type="text" size="small" class="text-danger" @click="deleteTodoItem(todo.id)">删除</el-button>
            </div>
          </div>
          <div v-if="todoItems.length === 0" class="empty-todo">
            暂无待办事项
          </div>
        </div>
      </el-card>

      <!-- 系统状态 -->
      <el-card class="system-status-card">
        <template #header>
          <div class="card-header">
            <span>系统状态</span>
          </div>
        </template>
        <div class="system-status">
          <div class="status-item">
            <span class="status-label">服务器状态:</span>
            <span class="status-value online">正常</span>
          </div>
          <div class="status-item">
            <span class="status-label">数据库状态:</span>
            <span class="status-value online">正常</span>
          </div>
          <div class="status-item">
            <span class="status-label">内存使用率:</span>
            <el-progress :percentage="memoryUsage" :status="getProgressStatus(memoryUsage)" :stroke-width="8" />
          </div>
          <div class="status-item">
            <span class="status-label">CPU使用率:</span>
            <el-progress :percentage="cpuUsage" :status="getProgressStatus(cpuUsage)" :stroke-width="8" />
          </div>
          <div class="status-item">
            <span class="status-label">磁盘使用率:</span>
            <el-progress :percentage="diskUsage" :status="getProgressStatus(diskUsage)" :stroke-width="8" />
          </div>
          <div class="status-item">
            <span class="status-label">系统版本:</span>
            <span class="status-value">{{ systemVersion }}</span>
          </div>
          <div class="status-item">
            <span class="status-label">最后备份:</span>
            <span class="status-value">{{ lastBackupTime }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加待办事项模态框 -->
    <el-dialog v-model="showAddTodoModal" title="添加待办事项" width="400px">
      <el-input
        v-model="newTodoContent"
        type="textarea"
        rows="3"
        placeholder="请输入待办事项内容"
      />
      <template #footer>
        <el-button @click="showAddTodoModal = false">取消</el-button>
        <el-button type="primary" @click="confirmAddTodo">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑待办事项模态框 -->
    <el-dialog v-model="showEditTodoModal" title="编辑待办事项" width="400px">
      <el-input
        v-model="editingTodo.content"
        type="textarea"
        rows="3"
        placeholder="请输入待办事项内容"
      />
      <template #footer>
        <el-button @click="showEditTodoModal = false">取消</el-button>
        <el-button type="primary" @click="confirmEditTodo">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Chart } from 'chart.js';

// 统计数据
const totalUsers = ref(12548);
const totalPosts = ref(28652);
const totalQuestions = ref(15820);
const totalGroups = ref(326);
const totalResources = ref(8973);
const totalVisits = ref(5862);

// 增长趋势
const userGrowth = ref(12.5);
const postGrowth = ref(8.3);
const questionGrowth = ref(15.2);
const groupGrowth = ref(6.7);
const resourceGrowth = ref(9.1);
const visitTrend = ref(18.4);

// 图表筛选
const chartTimeRange = ref('30d');
const activeUserFilter = ref('region');

// 系统状态
const memoryUsage = ref(65);
const cpuUsage = ref(42);
const diskUsage = ref(78);
const systemVersion = ref('v2.3.1');
const lastBackupTime = ref('2024-05-10 02:30:00');

// 图表引用
const userGrowthChart = ref<HTMLCanvasElement | null>(null);
const userDistributionChart = ref<HTMLCanvasElement | null>(null);

// 最近活动数据
const recentActivities = ref([
  { id: 1, type: 'user', content: '用户 "行测大神" 注册了账号', time: '5分钟前' },
  { id: 2, type: 'post', content: '用户 "申论小王子" 发布了新帖子 《2024年国考申论真题解析及参考答案》', time: '30分钟前' },
  { id: 3, type: 'question', content: '用户 "题库管理员" 添加了10道新题目', time: '1小时前' },
  { id: 4, type: 'comment', content: '用户 "公考小白" 评论了帖子 《行测判断推理技巧分享》', time: '2小时前' },
  { id: 5, type: 'group', content: '用户 "学习小组" 创建了新的学习小组 "2024省考冲刺班"', time: '3小时前' },
  { id: 6, type: 'resource', content: '用户 "资料共享" 上传了新资源 《2024年最新时政热点汇总》', time: '5小时前' },
  { id: 7, type: 'system', content: '系统进行了自动备份', time: '昨天 23:45' },
  { id: 8, type: 'moderation', content: '管理员 "超级管理员" 删除了违规帖子', time: '昨天 18:30' }
]);

// 待办事项
const todoItems = ref([
  { id: 1, content: '审核新用户注册申请', completed: false },
  { id: 2, content: '处理用户举报的帖子', completed: false },
  { id: 3, content: '更新系统题库', completed: true },
  { id: 4, content: '查看系统日志', completed: false },
  { id: 5, content: '准备下周的运营活动', completed: false }
]);

// 模态框控制
const showAddTodoModal = ref(false);
const showEditTodoModal = ref(false);

// 新待办事项内容
const newTodoContent = ref('');
const editingTodo = ref<any>(null);

// 图表实例
let userGrowthChartInstance: Chart | null = null;
let userDistributionChartInstance: Chart | null = null;

// 获取活动图标类
const getActivityIconClass = (type: string) => {
  const iconClassMap: Record<string, string> = {
    user: 'text-blue-500',
    post: 'text-green-500',
    question: 'text-purple-500',
    comment: 'text-yellow-500',
    group: 'text-pink-500',
    resource: 'text-orange-500',
    system: 'text-gray-500',
    moderation: 'text-red-500'
  };
  return iconClassMap[type] || 'text-gray-500';
};

// 获取活动图标
const getActivityIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    user: 'User',
    post: 'Message',
    question: 'Document',
    comment: 'ChatDotSquare',
    group: 'UserFilled',
    resource: 'Folder',
    system: 'Setting',
    moderation: 'Warning'
  };
  return iconMap[type] || 'HelpFilled';
};

// 获取进度条状态
const getProgressStatus = (percentage: number) => {
  if (percentage > 80) return 'exception';
  if (percentage > 60) return 'warning';
  return 'success';
};

// 初始化用户增长图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return;
  
  const ctx = userGrowthChart.value.getContext('2d');
  if (!ctx) return;
  
  // 销毁已存在的图表
  if (userGrowthChartInstance) {
    userGrowthChartInstance.destroy();
  }
  
  // 生成模拟数据
  const labels = [];
  const data = [];
  const now = new Date();
  
  if (chartTimeRange.value === '7d') {
    for (let i = 6; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
      data.push(10000 + Math.floor(Math.random() * 2000));
    }
  } else if (chartTimeRange.value === '30d') {
    for (let i = 29; i >= 0; i -= 3) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
      data.push(9500 + Math.floor(Math.random() * 3000));
    }
  } else if (chartTimeRange.value === '90d') {
    for (let i = 89; i >= 0; i -= 10) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
      data.push(9000 + Math.floor(Math.random() * 3500));
    }
  } else if (chartTimeRange.value === '12m') {
    for (let i = 11; i >= 0; i--) {
      const date = new Date(now);
      date.setMonth(date.getMonth() - i);
      labels.push(`${date.getFullYear()}/${date.getMonth() + 1}`);
      data.push(7000 + Math.floor(Math.random() * 5000));
    }
  }
  
  userGrowthChartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: '用户数量',
        data,
        borderColor: '#6366f1',
        backgroundColor: 'rgba(99, 102, 241, 0.1)',
        tension: 0.3,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: false,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
};

// 初始化用户分布图表
const initUserDistributionChart = () => {
  if (!userDistributionChart.value) return;
  
  const ctx = userDistributionChart.value.getContext('2d');
  if (!ctx) return;
  
  // 销毁已存在的图表
  if (userDistributionChartInstance) {
    userDistributionChartInstance.destroy();
  }
  
  // 根据筛选条件生成不同的数据
  let labels: string[] = [];
  let data: number[] = [];
  let backgroundColor: string[] = [];
  
  if (activeUserFilter.value === 'region') {
    labels = ['北京', '上海', '广州', '深圳', '杭州', '其他'];
    data = [25, 18, 15, 12, 10, 20];
    backgroundColor = ['#6366f1', '#8b5cf6', '#ec4899', '#f43f5e', '#eab308', '#64748b'];
  } else if (activeUserFilter.value === 'interest') {
    labels = ['行测', '申论', '面试', '公基', '专业科目', '其他'];
    data = [35, 25, 15, 10, 8, 7];
    backgroundColor = ['#10b981', '#3b82f6', '#8b5cf6', '#ec4899', '#f43f5e', '#64748b'];
  } else if (activeUserFilter.value === 'role') {
    labels = ['普通用户', 'VIP用户', '版主', '管理员', '游客'];
    data = [75, 15, 5, 2, 3];
    backgroundColor = ['#3b82f6', '#8b5cf6', '#ec4899', '#f43f5e', '#64748b'];
  }
  
  userDistributionChartInstance = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels,
      datasets: [{
        data,
        backgroundColor,
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'right'
        }
      }
    }
  });
};

// 查看全部活动
const viewAllActivities = () => {
  ElMessage.info('查看全部活动功能待实现');
};

// 添加待办事项
const addTodoItem = () => {
  newTodoContent.value = '';
  showAddTodoModal.value = true;
};

// 确认添加待办事项
const confirmAddTodo = () => {
  if (!newTodoContent.value.trim()) {
    ElMessage.warning('请输入待办事项内容');
    return;
  }
  
  const newTodo = {
    id: Date.now(),
    content: newTodoContent.value.trim(),
    completed: false
  };
  
  todoItems.value.unshift(newTodo);
  showAddTodoModal.value = false;
  ElMessage.success('待办事项添加成功');
};

// 编辑待办事项
const editTodoItem = (todo: any) => {
  editingTodo.value = { ...todo };
  showEditTodoModal.value = true;
};

// 确认编辑待办事项
const confirmEditTodo = () => {
  if (!editingTodo.value || !editingTodo.value.content.trim()) {
    ElMessage.warning('请输入待办事项内容');
    return;
  }
  
  const index = todoItems.value.findIndex(item => item.id === editingTodo.value.id);
  if (index !== -1) {
    todoItems.value[index] = editingTodo.value;
    showEditTodoModal.value = false;
    ElMessage.success('待办事项更新成功');
  }
};

// 更新待办事项状态
const updateTodoStatus = (todo: any) => {
  const index = todoItems.value.findIndex(item => item.id === todo.id);
  if (index !== -1) {
    todoItems.value[index] = { ...todo };
    ElMessage.success('待办事项状态已更新');
  }
};

// 删除待办事项
const deleteTodoItem = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除此待办事项吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    todoItems.value = todoItems.value.filter(item => item.id !== id);
    ElMessage.success('待办事项已删除');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 监听图表筛选变化
chartTimeRange.value = '30d';
activeUserFilter.value = 'region';

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initUserGrowthChart();
    initUserDistributionChart();
  });
});
</script>

<style lang="scss" scoped>
.admin-dashboard-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 5px 0 0 0;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 5px;
}

.stat-trend {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 20px;
}

.trend-value {
  font-size: 16px;
  font-weight: 600;
}

.trend-value.positive {
  color: #10b981;
}

.trend-value.negative {
  color: #f43f5e;
}

.trend-label {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
}

.stat-icon {
  font-size: 36px;
  color: #6366f1;
  opacity: 0.1;
  position: absolute;
  right: 20px;
  bottom: 10px;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
}

.chart-card {
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.chart-filter {
  width: 150px;
}

.chart-container {
  height: 300px;
  padding: 20px;
}

.dashboard-bottom {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 30px;
}

.activity-card,
.todo-card,
.system-status-card {
  border-radius: 8px;
  overflow: hidden;
}

.activities-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px 20px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #f9fafb;
  }
}

.activity-icon {
  font-size: 24px;
  margin-top: 2px;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 14px;
  color: #1f2937;
  margin: 0 0 5px 0;
  line-height: 1.5;
}

.activity-time {
  font-size: 12px;
  color: #9ca3af;
  margin: 0;
}

.todo-list {
  padding: 10px 20px 20px 20px;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f3f4f6;

  &:last-child {
    border-bottom: none;
  }
}

.todo-actions {
  display: flex;
  gap: 5px;
}

.empty-todo {
  text-align: center;
  color: #9ca3af;
  padding: 40px 20px;
}

.system-status {
  padding: 20px;
}

.status-item {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.status-label {
  display: block;
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 10px;
}

.status-value {
  font-size: 14px;
  color: #1f2937;
}

.status-value.online {
  color: #10b981;
  font-weight: 500;
}

.status-value.offline {
  color: #f43f5e;
  font-weight: 500;
}

// 响应式设计
@media (max-width: 1200px) {
  .stats-overview {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .dashboard-bottom {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .admin-dashboard-view {
    padding: 10px;
  }
  
  .stats-overview {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .chart-filter {
    width: 100%;
  }
}
</style>